package per.qiao.simplerest.returenvalue;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Company: 上海数惠系统技术有限公司
 * Department: 数据中心
 * Date: 2020-06-01 16:25
 *
 * @Author: qyp
 * Email: qiaoyp@dist.com.cn
 * Desc: 对于返回Collection集合，返回值只有一个泛型的结果做处理
 */
public class DefaultValueHandler implements ReturnValueHandler {

    @Override
    public boolean support(Object returnValue) {
        return returnValue != null && returnValue instanceof Collection;
    }

    @Override
    public Object handle(Object returnValue, Class returnType, Class genericType) {


        ObjectMapper mapper = new ObjectMapper();

        List<Object> returnList = new ArrayList<>();
        List<?> resultList = (List<?>) returnValue;
        for (Object o : resultList) {
            Object item = null;
            if (genericType != null) {
                item = mapper.convertValue(o, genericType);
            } else if (returnType != null) {
                item = mapper.convertValue(o, returnType);
            }
            returnList.add(item);
        }
        return returnList;
    }
}
